<template>
  <div :class="{'mobile-energy-edit-container': showMobilePage}" class="energy-edit-container">
    <SectionTitle title="精力分配表" style="margin: 12px 0 16px;">
      <el-tooltip placement="top" effect="dark">
        <div slot="content" style="max-width: 120px; line-height: 1.5; cursor: pointer">{{ ratioTips }}</div>
        <tipIcon is-diy style="margin-left: 8px"/>
      </el-tooltip>
      <div class="all-ratio">
        <img :src="energyIcon" alt="">
        总精力分配比例：<span class="text">{{ allRatio }}%</span>
      </div>
      <div v-if="!showMobilePage" class="options-btn-group">
        <PlainCreateBtn @click="createNewRow">新增</PlainCreateBtn>
        <el-button size="small" @click="pushLastData">填充上次</el-button>
        <el-button size="small" @click="resourceDrawerOpen">批量新增</el-button>
        <el-button :disabled="deleteDisable" size="small" type="danger" plain class="option-btn" @click="handleRowsDel">删除</el-button>
      </div>
    </SectionTitle>
    <template v-if="showMobilePage">
      <div class="mb12">
        <el-button size="small" @click="pushLastData">填充上次</el-button>
        <PlainCreateBtn @click="createNewRow">新增</PlainCreateBtn>
      </div>
      <div>
        <el-button size="small" @click="resourceDrawerOpen">批量新增</el-button>
        <el-button :disabled="deleteDisable" size="small" type="danger" plain class="option-btn" @click="handleRowsDel">删除</el-button>
      </div>
    </template>
    <dynamicEditTable
      v-loading="editTableLoading || !isEditSwitch"
      ref="dynamicEditTableRef"
      v-model="orders"
      :list-data="orders"
      :list-setting="editTableColumn"
      :show-add-btn="false"
      :default-params="defaultParams"
      :order-private-id="orderPrivateId"
      :table-max-height="tableMaxHeight"
      :non-copy-key="nonCopyKey"
      :cur-page="curPage"
      :per-page="perPage"
      :platform-option="platformOption"
      :fixed="showMobilePage ? false : 'right'"
      copy-to-next-row
      show-selection
      visible-change-data
      can-empty
      style="margin-top: 16px"
      @toReadModel="toReadModel"
      @onSelectChange="getCurIds"
      @selectChange="dropdownBoxChange"
      @datePickerChange="datePickerChange"
      @orderPrivateIdChange="orderPrivateIdChange"
      @scrollSelectChange="scrollSelectChange"
      @scrollSelectClear="scrollSelectClear"
      @changeInputNumberData="changeInputNumberData"
      @onRowDel="onRowDel"
    />

    <ResourceDrawer ref="resourceDrawer" @editSwitch="editSwitch" @getResources="getResources" />
    <fixed-pagination>
      <div class="pagination-box">
        <div class="center">
          <el-button :loading="isSubmit" :disable="isSubmit" type="primary" size="small" @click="handleSubmit()">提交</el-button>
          <el-button type="info" class="cancel-btn-style" size="small" @click="handleCancel()">取消</el-button>
        </div>
        <el-pagination
          slot="pager"
          :current-page="curPage"
          :page-size="perPage"
          :total="orders.length"
          :page-sizes="[10, 20, 50]"
          layout="total, prev, pager, next, sizes, jumper"
          @size-change="pageSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </fixed-pagination>
  </div>
</template>

<script>
import SectionTitle from '@/components/Title';
import dynamicEditTable from '../components/editTable';
import { platformList } from '@/api/select';
import { getInfo } from '@/api/login';
import { mapState } from 'vuex';
import { PER_PAGE } from '@/utils/const';
import { getDeptName } from '@/utils';
import { storeEnergyDetailList, energyDetailList, getEnergyLastData } from '@/api/energy';
import { getEnergyTypeList, getProjectTypeList, getProjectOrderList } from '@/api/energy';
import ResourceDrawer from '@/components/Common/resourceDrawer';
import { showModal } from '@/utils/message';
import { getDepartmentAll } from '@/api/config';
import energyIcon from '@/assets/energy.png';
export default {
  name: 'EnergyDetail',
  components: {
    SectionTitle,
    ResourceDrawer,
    dynamicEditTable
  },
  data() {
    return {
      energyIcon,
      antiShakeTime: 0, // 防抖时间
      editAll: 0,
      isEdit: false,
      isEditSwitch: true,
      energyId: '',
      processId: '',
      perPage: PER_PAGE,
      curPage: 1,
      orders: [],
      curSelectedIds: [],
      platformOption: [], // 下单平台
      deptTreeList: [], // 所属经营体
      deleteIds: [], // 被删除的id
      deleteDisable: true,
      orderPrivateId: 1,
      loading: false,
      editTableLoading: false,
      canSubmitEmpty: false, // 能否提交空表单
      energyTypeOptions: [],
      projectTypeOptions: [],
      isSubmit: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    allRatio() { // 总比例
      return this.orders.filter(el => !!el.allocationRatio).reduce((sum, item) => sum + item.allocationRatio * 1, 0).toFixed(2);
    },
    tableMaxHeight() {
      return window.innerHeight - 188;
    },
    setPerBtnDisabled() {
      return this.curPage === 1;
    },
    ratioTips() {
      return '运营人员的精力分配比例总和必须等于100%';
    },
    setNextBtnDisabled() {
      return (this.curPage * this.perPage) - this.orders.length >= 0;
    },
    editTableColumn() {
      return [{
        label: '精力类型',
        type: 'select',
        width: '120px',
        keyword: 'energyTypeId',
        renderKeyword: 'energyType',
        isRequired: true,
        keyName: 'id',
        tipKey: 'energyTypeDesc',
        labelName: 'energyType',
        options: this.energyTypeOptions
      }, {
        label: '下单平台',
        type: 'select',
        width: '120px',
        keyword: 'platformId',
        renderKeyword: 'orderPlatform',
        isRequired: true,
        // fitKeyDisabled: { key: 'energyType', value: '项目' },
        keyName: 'id',
        labelName: 'value',
        options: this.platformOption
      }, {
        label: '账号/项目名称',
        width: '180px',
        type: 'resourceOrProject',
        keyword: 'resourceId',
        keyName: 'mediumId',
        labelName: 'resourceName',
        scrollKeyword: 'projectId',
        scrollKeyName: 'id',
        foot: 'projectNum',
        footTag: '()',
        scrollLabelName: 'projectName',
        selectKeyword: 'projectTypeId',
        selectKeyName: 'id',
        selectLabelName: 'projectType',
        isRequired: true,
        loadmoreMethod: getProjectOrderList,
        projectTypeOptions: this.projectTypeOptions,
        isDynamicLoad: true
      },
      {
        label: '运营人员',
        type: 'cacheSelect',
        width: '120px',
        keyword: 'operatorId',
        isRequired: true,
        keyName: 'id',
        labelName: 'userName',
        renderKeyword: 'userName',
        associatedKeys: ['resourceId', 'projectTypeId', 'projectId'],
        options: [],
        showCheckUser: true,
        isDynamicLoad: true,
        extendParams: {
          type: 1
        }
      },
      {
        label: '精力分配比例',
        width: '120px',
        type: 'inputNumber',
        maxlength: 64,
        isRequired: true,
        keyword: 'allocationRatio',
        unit: '%',
        maxnumber: 100,
        isPositiveNumber: true,
        defaultEmpty: '--'
      }, {
        label: '所属经营体',
        type: 'cascader',
        width: '150px',
        renderKeyword: 'attributionMatrix',
        keyword: 'attributionMatrixId',
        showAllLevels: false,
        emitPath: false,
        checkStrictly: true,
        isRequired: true,
        keyName: 'id',
        labelName: 'name',
        options: this.deptTreeList,
        placeholder: '--'
      }, {
        label: '备注',
        width: '130px',
        type: 'inputText',
        maxlength: 200,
        isRequired: false,
        keyword: 'remark',
        defaultEmpty: '--'
      }, {
        label: '入职时间',
        type: 'datepicker',
        pickerFormat: 'yyyy/MM/dd',
        placeholder: '',
        width: '140px',
        keyword: 'entryTime',
        formatStr: 'YYYY/MM/DD'
      }, {
        label: '离职时间',
        type: 'datepicker',
        pickerFormat: 'yyyy/MM/dd',
        placeholder: '',
        width: '140px',
        keyword: 'dimissionTime',
        formatStr: 'YYYY/MM/DD'
      }, {
        label: '调岗时间',
        type: 'datepicker',
        pickerFormat: 'yyyy/MM/dd',
        placeholder: '',
        width: '140px',
        keyword: 'transferTime',
        formatStr: 'YYYY/MM/DD'
      }, {
        label: '更新人',
        width: '130px',
        type: 'inputText',
        disabled: true,
        keyword: 'updater',
        placeholder: '--'
      }, {
        label: '更新时间',
        type: 'datepicker',
        pickerFormat: 'yyyy/MM/dd HH:mm',
        placeholder: '--',
        disabled: true,
        width: '180px',
        keyword: 'updateTime',
        formatStr: 'YYYY/MM/DD HH:mm'
      }];
    },
    defaultClearKeys() { // 设置行信息移除项
      return ['operatorId', 'userName', 'attributionMatrixId', 'attributionMatrix', 'entryTime', 'dimissionTime', 'transferTime'];
    },
    nonCopyKey() {
      return ['id', 'updater', 'updaterId', 'updateTime'];
    },
    defaultEnergyType() {
      const energyTypeItem = this.energyTypeOptions.find(e => e.energyType === '账号');
      return energyTypeItem ? {
        energyTypeId: energyTypeItem.id,
        energyType: '账号'
      } : {};
    },
    defaultParams() {
      return {
        ...this.defaultEnergyType,
        customizeState: true
      };
    }
  },
  created() {
    this.initEnergyId();
    this.queryDetailList();
    this.queryPlatformList(); // 下单平台
    this.queryDeptTreeList(); // 所属经营体
    this.getEnergyTypeList(); // 精力类型
    this.getProjectTypeList(); // 项目类型
  },
  methods: {
    initEnergyId() {
      this.energyId = this.$route.query.energyId;
      this.processId = this.$route.query.processId;
      this.editAll = this.$route.query.editAll;
      if (!this.energyId) {
        this.$message.warning('无法获取ID');
        this.$router.back();
      }
    },
    getEnergyTypeList() {
      getEnergyTypeList().then(res => {
        if (res.code === 200) {
          this.energyTypeOptions = res.data;
        }
      }).catch(err => {
        console.log(err);
      });
    },
    getProjectTypeList() {
      getProjectTypeList().then(res => {
        if (res.code === 200) {
          this.projectTypeOptions = res.data;
        }
      }).catch(err => {
        console.log(err);
      });
    },

    queryDetailList() {
      this.editTableLoading = true;
      const params = Object.create(null);
      params.isCurCreator = Number(this.editAll) ? 0 : 1;
      params.page = 1;
      params.perPage = 999999999;
      params.id = this.energyId;
      energyDetailList(params).then(res => {
        if (res.code === 200) {
          res.data.items.forEach(item => {
            item.orderPrivateId = ++this.orderPrivateId;
          });
          if (res.data.items.length) {
            res.data.items.forEach(el => { el.onlyRead = true; });
            this.orders = res.data.items;
            this.canSubmitEmpty = true;
          } else {
            this.orders.push({
              customizeState: true,
              orderPrivateId: 1
            });
          }
        }
        this.editTableLoading = false;
      }).catch(_ => {
        this.editTableLoading = false;
      });
    },
    async queryPlatformList() {
      try {
        const result = await platformList();
        this.platformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(_ => {});
    },
    pageSizeChange(num) {
      this.perPage = num;
      this.toReadModel();
    },
    handleCurrentChange(num) {
      this.toReadModel();
      this.curPage = num;
      this.$nextTick(() => {
        const tableScrollDom = document.querySelector('.el-table__body-wrapper');
        tableScrollDom && (tableScrollDom.scrollTop = 0);
      });
    },
    handleJumpPage(isNext = true) {
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.toReadModel();
      this.antiShakeTime = timestamp;
      isNext ? ++this.curPage : --this.curPage;
      this.$nextTick(() => {
        const tableScrollDom = document.querySelector('.el-table__body-wrapper');
        tableScrollDom && (tableScrollDom.scrollTop = 0);
      });
    },
    createNewRow() {
      this.$refs['dynamicEditTableRef'].addValue(true);
      this.curPage = 1;
    },
    // 批量新增
    resourceDrawerOpen() {
      this.$refs['resourceDrawer'].openDrawer();
      /**
       * 因为批量添加时表格中的下拉框、输入框占用了大量内存，导致页面卡顿，所以添加时关闭编辑模式，添加完后再开启
       */
      this.isEditSwitch = false;
    },
    getResources(data) {
      const list = JSON.parse(JSON.stringify(data));
      list.forEach((item, index) => {
        item.onlyRead = true;
        item.orderPrivateId = ++this.orderPrivateId;
        item.platformId = item.platformType;
        item.orderPlatform = item.platformTypeName;
        let setUserIndex = 0;
        let userId = this.userInfo.id;
        let userName = this.userInfo.userName;
        if (Array.isArray(item.totalOperation) && item.totalOperation.length) {
          if (index !== -1) {
            const operatorIndex = item.totalOperation.findIndex(item => item.id === this.userInfo.id);
            setUserIndex = operatorIndex === -1 ? 0 : operatorIndex;
            userId = item.totalOperation[setUserIndex].id;
            userName = item.totalOperation[setUserIndex].value;
          }
        }
        this.setUserInfo(userId, index, list);
        item.attributionMatrixId = item.attributionMatrix;
        item.attributionMatrix = item.attributionMatrixName;
        item.resourceId = item.mediumId;
        item.updateTime = '';
        item.operatorId = userId; // 运营人员
        item.userName = userName; // 运营人员默认展示label
        item.energyType = this.defaultEnergyType.energyType;
        item.energyTypeId = this.defaultEnergyType.energyTypeId;
      });
      this.orders.unshift(...list);
    },
    toReadModel() {
      this.orders.forEach(el => { el.onlyRead = true; });
    },
    editSwitch(status) {
      setTimeout(() => {
        this.isEditSwitch = status;
      }, 0);
    },
    modelChange() {
      this.isEdit = !this.isEdit;
    },
    // 填充上次
    pushLastData() {
      this.editTableLoading = true;
      getEnergyLastData({ id: this.energyId }).then(res => {
        if (res.code === 200) {
          res.data.forEach(item => {
            item.orderPrivateId = ++this.orderPrivateId;
            item.id = null;
          });
          this.orders.unshift(...res.data);
          this.toReadModel();
          this.editTableLoading = false;
        }
      }).catch(_ => {
        this.editTableLoading = false;
      });
    },
    handleRowsDel() {
      this.$confirm('确认删除已选中的数据吗？', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        let curRow;
        // eslint-disable-next-line no-cond-assign
        while (curRow = this.curSelectedIds.pop()) {
          for (let index = this.orders.length - 1; index >= 0; index--) {
            const curId = curRow.id ? 'id' : 'orderPrivateId';
            if (this.orders[index][curId] === curRow[curId]) {
              curId === 'id' && this.deleteIds.push(curRow[curId]);
              this.orders.splice(index, 1);
            }
          }
        }
      });
    },
    // 获取当前行数据下标
    getCurRowIndex(rowData, specifyID = '') {
      if (specifyID) { // 指定id
        return this.orders.findIndex(item => item[specifyID] === rowData[specifyID]);
      }
      if (rowData.id) {
        return this.orders.findIndex(item => item.id === rowData.id);
      }
      return this.orders.findIndex(item => item.orderPrivateId === rowData.orderPrivateId);
    },
    // 重置行部分信息
    resetRowData(data, extendClearKeys = []) {
      const index = this.getCurRowIndex(data);
      if (index !== -1) {
        let clearKeys = JSON.parse(JSON.stringify(this.defaultClearKeys));
        if (extendClearKeys.length) {
          clearKeys = clearKeys.concat(extendClearKeys);
        }
        clearKeys.forEach(key => {
          this.orders[index][key] && this.$set(this.orders[index], key, '');
        });
      }
    },
    onRowDel(rowData) {
      rowData.id && this.deleteIds.push(rowData.id);
      if (this.orders.length <= (this.curPage - 1) * this.perPage) {
        this.curPage > 1 && --this.curPage;
      }
    },
    // 切换下拉数据
    dropdownBoxChange(data) {
      const rowIndex = this.getCurRowIndex(data.item);
      switch (data.key) {
        case 'energyTypeId': // 精力类型
          this.resetRowData(data.item, ['platformId', 'orderPlatform', 'resourceId', 'resourceName', 'projectTypeId', 'projectType', 'allocationRatio']);
          this.$set(this.orders[rowIndex], 'energyType', data.item[data.key] ? this.energyTypeOptions.find(e => e.id === data.item[data.key]).energyType : '');
          break;
        case 'platformId': // 下单平台
          this.resetRowData(data.item, ['resourceId', 'resourceName']);
          this.$set(this.orders[rowIndex], 'orderPlatform', data.item[data.key] ? this.platformOption.filter(el => el.id === data.item.platformId)[0].value : '');
          break;
        case 'resourceId': // 账号名称
          this.resetRowData(data.item);
          break;
        case 'projectTypeId': // 项目名称
          this.resetRowData(data.item);
          this.$set(this.orders[rowIndex], 'projectType', data.item[data.key] || data.item[data.key] === 0 ? this.projectTypeOptions.find(e => e.id === data.item[data.key]).projectType : '');
          if (this.orders[rowIndex]['projectType'] === '物料投放的账号主运营（整合热搜案项目）') {
            this.$set(this.orders[rowIndex], 'allocationRatio', 1);
          }
          if (!data.item[data.key] && data.item[data.key] !== 0) this.$set(this.orders[rowIndex], 'allocationRatio', null);
          if (data.item[data.key] || data.item[data.key] === 0) {
            this.$set(this.orders[rowIndex], 'operatorId', this.userInfo.id); // 运营人员
            this.$set(this.orders[rowIndex], 'userName', this.userInfo.userName); // 账号默认展示label
          }
          break;
        case 'operatorId': // 运营人员
          this.setUserInfo(data.item.operatorId, rowIndex);
          break;
        case 'attributionMatrixId': // 所属经营体
          this.$set(this.orders[rowIndex], 'attributionMatrix', data.item[data.key] ? getDeptName(data.item.attributionMatrixId, this.deptTreeList) : '');
          break;
        case 'projectId': // 项目订单id
          if (data.item[data.key] || data.item[data.key] === 0) {
            this.$set(this.orders[rowIndex], 'operatorId', this.userInfo.id); // 运营人员
            this.$set(this.orders[rowIndex], 'userName', this.userInfo.userName); // 账号默认展示label
          } else {
            this.resetRowData(data.item, ['projectNum', 'projectName']);
          }
          break;
      }
    },
    // 切换账号/运营人员
    scrollSelectChange(keyword, data) {
      let index;
      index = this.getCurRowIndex(data, 'orderPrivateId');
      switch (keyword) {
        // 切换账号 有运营人员：默认选中当前用户/选中第一个；无运营人员：塞入当前用户
        case 'resourceId':
          this.$nextTick(() => {
            let setUserIndex = 0;
            let userId = this.userInfo.id;
            let userName = this.userInfo.userName;
            if (Array.isArray(data.totalOperation) && data.totalOperation.length) {
              if (index !== -1) {
                const operatorIndex = data.totalOperation.findIndex(item => item.id === this.userInfo.id);
                setUserIndex = operatorIndex === -1 ? 0 : operatorIndex;
                userId = data.totalOperation[setUserIndex].id;
                userName = data.totalOperation[setUserIndex].value;
              }
            } else {
              userId = this.userInfo.id;
              userName = this.userInfo.userName;
            }
            this.$set(this.orders[index], 'attributionMatrixId', data.attributionMatrix); // 所属经营体
            this.$set(this.orders[index], 'attributionMatrix', data.attributionMatrixName); // 所属经营体
            this.$set(this.orders[index], 'orderPlatform', data.platformTypeName); // 下单平台
            this.$set(this.orders[index], 'operatorId', userId); // 运营人员
            this.$set(this.orders[index], 'resourceName', data.resourceName); // 账号默认展示label
            this.$set(this.orders[index], 'userName', userName); // 运营人员默认展示label
            this.setUserInfo(userId, index);
          });
          break;
        case 'operatorId': // 运营人员
          index = this.getCurRowIndex(data, 'orderPrivateId');
          this.$set(this.orders[index], 'userName', data.userName);
          break;
        case 'projectId': // 项目订单id
          this.$set(this.orders[index], 'projectName', data.projectName);
          this.$set(this.orders[index], 'projectNum', data.projectNum);
          break;
      }
    },
    scrollSelectClear(keyword, rowData) {
      const index = this.getCurRowIndex(rowData);
      if (keyword === 'resourceId') {
        this.$set(this.orders[index], 'resourceName', '');
      }
      this.$set(this.orders[index], 'userName', '');
    },
    // 精力类型为项目时，需校验输入比例是否符合配置的比例区间
    changeInputNumberData({ item, key }) {
      if (['账号', '项目订单'].includes(item.energyType)) return;
      const index = this.getCurRowIndex(item, 'orderPrivateId');
      if (key === 'allocationRatio') {
        const currentProjectType = this.projectTypeOptions.find(e => e.projectType === item.projectType) || {};
        if ((item[key] || item[key] === 0) && (item[key] < currentProjectType.startRate || item[key] > currentProjectType.endRate)) {
          this.$message.warning(`请输入${currentProjectType.startRate}%-${currentProjectType.endRate}%的分配比例`);
          this.$set(this.orders[index], key, '');
        }
      }
    },
    // 切换运营人员-设置用户信息相关的行数据
    setUserInfo(id, index, list = this.orders) {
      if (!id) {
        list[index].entryTime && (list[index].entryTime = '');
        list[index].dimissionTime && (list[index].dimissionTime = '');
      } else {
        getInfo(id).then(res => {
          if (res.code === 200) {
            this.$set(list[index], 'entryTime', this.getTimeStamp(res.data.entryTime));
            this.$set(list[index], 'dimissionTime', this.getTimeStamp(res.data.dimissionTime));
          }
        }).catch(_ => {
        });
      }
      list[index].transferTime && (list[index].transferTime = '');
    },
    // 获取时间戳
    getTimeStamp(val) {
      if (!val) return;
      return Number(val) * 1000;
    },
    // 切换时间
    datePickerChange(data) {
      const rowIndex = this.getCurRowIndex(data.item);
      switch (data.key) {
        case 'entryTime':
        case 'dimissionTime':
          if (data.item.dimissionTime && data.item.entryTime) {
            if (Number(data.item.dimissionTime) < Number(data.item.entryTime)) {
              this.$message.warning('离职时间不能早于入职时间');
              this.orders[rowIndex][data.key] = '';
            }
          }
          this.validateTransferTime(data, rowIndex);
          break;
        case 'transferTime':
          this.validateTransferTime(data, rowIndex);
          break;
      }
    },
    validateTransferTime(data, rowIndex) {
      if (data.item.transferTime) {
        if (data.item.entryTime && Number(data.item.transferTime) < Number(data.item.entryTime)) {
          this.$message.warning('调岗时间不能早于入职时间');
          this.orders[rowIndex]['transferTime'] = '';
        } else if (data.item.dimissionTime && Number(data.item.transferTime) > Number(data.item.dimissionTime)) {
          this.$message.warning('调岗时间不能晚于离职时间');
          this.orders[rowIndex]['transferTime'] = '';
        }
      }
    },
    getCurIds(ids) {
      this.deleteDisable = !(Array.isArray(ids) && ids.length);
      this.curSelectedIds = ids || [];
    },
    orderPrivateIdChange(num) {
      if (!num) return;
      this.orderPrivateId = num;
    },
    handleSubmit() {
      if (!this.orders.length && !this.canSubmitEmpty) {
        this.$message.warning('请填写表单后再提交');
        return;
      }
      this.$refs['dynamicEditTableRef'].validate().then(() => {
        const checkRatioResult = this.checkAllocationRatio();
        checkRatioResult && this.storeEditEnergy();
      }).catch(() => {
        this.$message.warning('请检查表单是否填写完整');
      });
      this.loading = false;
    },
    // 判断运营人员分配比例总和是否为100%
    checkAllocationRatio() {
      let isCorrect = true;
      for (let i = 0; i < this.orders.length; i++) {
        const { allocationRatio } = this.orders[i];
        if (allocationRatio && Number(allocationRatio) === 0) {
          isCorrect = false;
          this.$message.warning(`运营人员【${this.orders[i].userName}】存在精力分配比例为0%，请修改后再提交`);
          break;
        }
      }
      return isCorrect;
    },
    // 编辑提交
    storeEditEnergy() {
      this.isSubmit = true;
      setTimeout(() => {
        this.isSubmit = false;
      }, 1000);
      const params = Object.create(null);
      params.id = this.energyId;
      params.list = JSON.parse(JSON.stringify(this.orders));
      params.list.forEach(e => {
        e.applicativeType = this.getApplicativeType(e.energyType);
        delete e.projectName;
        delete e.projectNum;
      });
      params.deleteIds = this.deleteIds.join();
      storeEnergyDetailList(params).then(res => {
        if (res.code === 200) {
          this.$message.success('提交成功');
          this.$router.push({
            name: 'energyDetail',
            query: {
              energyId: this.energyId,
              processId: this.processId
            }
          });
        }
        if (res.code === 501) {
          this.getProjectTypeList();
          this.$message.error(res.message);
        }
      }).catch(err => {
        console.log(err);
      });
    },
    getApplicativeType(energyType) {
      // 1：账号 2：其他精力类型 3:项目订单
      return {
        '账号': 1,
        '项目订单': 3
      }[energyType] || 2;
    },
    handleCancel() {
      showModal('请确认是否离开，离开后将不保存本次编辑数据', '', {
        iconClass: 'del-icon'
      }).then(() => {
        this.$router.push({
          name: 'energyDetail',
          query: {
            energyId: this.energyId,
            processId: this.processId
          }
        });
      }).catch(() => {
        return false;
      });
    }
  }
};
</script>

<style scoped lang="scss">
.energy-edit-container {
  .el-icon-warning-outline:hover{
    color: #4064EF !important;
  }
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding: 16px 24px 55px;
  min-height: calc(100vh - 64px);
  .all-ratio{
    height: 32px;
    display: flex;
    align-items: center;
    font-size: 14px;
    margin-left: 8px;
    padding: 0 21px 0 4px;
    background: #FAFAFC;
    color: #999999;
    border-radius: 2px;
    img{
      width: 14px;
      height: 14px;
      margin-right: 8px;
      flex-shrink: 0;
    }
    .icon{
      margin-right: 8px;
    }
    .text{
      font-size: 16px;
      color: #5F77C3;
      font-weight: bold;
    }
  }
  .options-btn-group {
    position: absolute;
    right: 0;
    ::v-deep .el-button {
      padding-left: 12px;
      padding-right: 12px;
    }
  }
  ::v-deep .el-input--small .el-input__icon {
    display: flex;
    align-items: center;
    justify-content: center;
    line-height: 100%;
  }
  ::v-deep .edit-table-input-text {
    ::v-deep .el-input__inner {
      padding-right: 8px;
    }
  }
  ::v-deep .edit-input-number-allocationRatio {
    ::v-deep .el-input__inner {
      text-align: right;
      padding-right: 22px;
    }
  }
}
::v-deep .el-pagination {
  padding: 0 !important;
  display: flex;
  align-items: center;
}
.pagination-box {
  display: flex;
  align-items: center;
  width: 100%;
}
.mobile-energy-edit-container {
  margin: 0;
  padding: 12px 12px 55px;
}
</style>
